package com.ruoyi.web.controller.customer;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.quartz.util.CronUtils;
import com.ruoyi.quartz.util.ScheduleUtils;

/**
 * Customer权限定时任务信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/customer/job")
public class CustomerJobController extends BaseController
{
    @Autowired
    private ISysJobService jobService;

    /**
     * 查询定时任务列表（仅显示当前用户创建的任务）
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping("/list")
    public TableDataInfo list(SysJob sysJob)
    {
        startPage();
        // 只查询当前用户创建的任务
        sysJob.setCreateBy(getUsername());
        List<SysJob> list = jobService.selectJobList(sysJob);
        return getDataTable(list);
    }

    /**
     * 导出定时任务列表
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJob sysJob)
    {
        // 只导出当前用户创建的任务
        sysJob.setCreateBy(getUsername());
        List<SysJob> list = jobService.selectJobList(sysJob);
        ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
        util.exportExcel(response, list, "定时任务");
    }

    /**
     * 获取定时任务详细信息
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @GetMapping(value = "/{jobId}")
    public AjaxResult getInfo(@PathVariable("jobId") Long jobId)
    {
        SysJob job = jobService.selectJobById(jobId);
        if (job == null)
        {
            return error("任务不存在");
        }
        // 检查是否为当前用户创建的任务
        if (!getUsername().equals(job.getCreateBy()))
        {
            return error("无权限访问此任务");
        }
        return success(job);
    }

    /**
     * 创建HTTP请求定时任务
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.INSERT)
    @PostMapping("/createHttpTask")
    public AjaxResult createHttpTask(@RequestBody CreateHttpTaskRequest request) throws SchedulerException, TaskException
    {
        // 参数验证
        if (StringUtils.isEmpty(request.getApiUrl()))
        {
            return error("API接口地址不能为空");
        }
        
        if (StringUtils.isEmpty(request.getTaskName()))
        {
            return error("任务名称不能为空");
        }
        
        if (StringUtils.isEmpty(request.getCronExpression()))
        {
            return error("Cron表达式不能为空");
        }
        
        // 验证URL格式
        if (!request.getApiUrl().startsWith("http://") && !request.getApiUrl().startsWith("https://"))
        {
            return error("API接口地址必须以http://或https://开头");
        }
        
        // 验证Cron表达式
        if (!CronUtils.isValid(request.getCronExpression()))
        {
            return error("Cron表达式格式不正确");
        }
        
        // 创建定时任务对象
        SysJob job = new SysJob();
        job.setJobName(request.getTaskName());
        job.setJobGroup("CUSTOMER_HTTP_GROUP");
        // 设置调用目标：httpRequestTask.executeHttpRequest('URL')
        job.setInvokeTarget("httpRequestTask.executeHttpRequest('" + request.getApiUrl() + "')");
        job.setCronExpression(request.getCronExpression());
        job.setMisfirePolicy("3"); // 不触发立即执行
        job.setConcurrent("1"); // 禁止并发执行
        job.setStatus("0"); // 正常状态
        job.setCreateBy(getUsername());
        job.setRemark(request.getRemark());
        
        // 检查调用目标是否在白名单内
        if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return error("创建任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        
        return toAjax(jobService.insertJob(job));
    }

    /**
     * 修改定时任务
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysJob job) throws SchedulerException, TaskException
    {
        // 检查任务是否存在
        SysJob existingJob = jobService.selectJobById(job.getJobId());
        if (existingJob == null)
        {
            return error("任务不存在");
        }
        
        // 检查是否为当前用户创建的任务
        if (!getUsername().equals(existingJob.getCreateBy()))
        {
            return error("无权限修改此任务");
        }
        
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return error("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI))
        {
            return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS }))
        {
            return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constants.HTTP, Constants.HTTPS }))
        {
            return error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR))
        {
            return error("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return error("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setUpdateBy(getUsername());
        return toAjax(jobService.updateJob(job));
    }

    /**
     * 定时任务状态修改
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestBody SysJob job) throws SchedulerException
    {
        // 检查任务是否存在
        SysJob existingJob = jobService.selectJobById(job.getJobId());
        if (existingJob == null)
        {
            return error("任务不存在");
        }
        
        // 检查是否为当前用户创建的任务
        if (!getUsername().equals(existingJob.getCreateBy()))
        {
            return error("无权限修改此任务状态");
        }
        
        job.setUpdateBy(getUsername());
        return toAjax(jobService.changeStatus(job));
    }

    /**
     * 定时任务立即执行一次
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.UPDATE)
    @PutMapping("/run")
    public AjaxResult run(@RequestBody SysJob job) throws SchedulerException
    {
        // 检查任务是否存在
        SysJob existingJob = jobService.selectJobById(job.getJobId());
        if (existingJob == null)
        {
            return error("任务不存在");
        }
        
        // 检查是否为当前用户创建的任务
        if (!getUsername().equals(existingJob.getCreateBy()))
        {
            return error("无权限执行此任务");
        }
        
        boolean result = jobService.run(job);
        return result ? success() : error("任务执行失败");
    }

    /**
     * 删除定时任务
     */
    @PreAuthorize("@ss.hasRole('customer')")
    @Log(title = "定时任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{jobIds}")
    public AjaxResult remove(@PathVariable Long[] jobIds) throws SchedulerException
    {
        // 检查所有任务是否都是当前用户创建的
        for (Long jobId : jobIds)
        {
            SysJob existingJob = jobService.selectJobById(jobId);
            if (existingJob == null)
            {
                return error("任务ID " + jobId + " 不存在");
            }
            
            if (!getUsername().equals(existingJob.getCreateBy()))
            {
                return error("无权限删除任务ID " + jobId);
            }
        }
        
        jobService.deleteJobByIds(jobIds);
        return success();
    }
    
    /**
     * 创建HTTP任务请求对象
     */
    public static class CreateHttpTaskRequest
    {
        /** 任务名称 */
        private String taskName;
        
        /** API接口地址 */
        private String apiUrl;
        
        /** Cron表达式 */
        private String cronExpression;
        
        /** 备注 */
        private String remark;
        
        public String getTaskName()
        {
            return taskName;
        }
        
        public void setTaskName(String taskName)
        {
            this.taskName = taskName;
        }
        
        public String getApiUrl()
        {
            return apiUrl;
        }
        
        public void setApiUrl(String apiUrl)
        {
            this.apiUrl = apiUrl;
        }
        
        public String getCronExpression()
        {
            return cronExpression;
        }
        
        public void setCronExpression(String cronExpression)
        {
            this.cronExpression = cronExpression;
        }
        
        public String getRemark()
        {
            return remark;
        }
        
        public void setRemark(String remark)
        {
            this.remark = remark;
        }
    }
}